<?php
/*
 * kernel/object.user.php
 *
 * This code is distributed and used under the GNU GPL v2 License,
 * please, read file LICENSE, which is situated in root directory,
 * or in "LICENSE" directory with most acceptable translation for you
 *
 * users,groups, access lists
 *
 * Copyright (C) 2010, Taras Kudla
 *
 */


/*
 * Fixme: Need to refactor
 */

class gUser extends gKernel{

    private $UserTable      = "users";
    private $CookieLifeTime = 36000;
    private $inAlready      = false;
    private $userAccess 	= array(-1);
    private $userID     	= null;
    private $userGroup	= 0;
    private $UserName	="guest";
	
    public function init(){
        if($this->core->get("runmode")==_CONSOLE_RUNMODE){
            return null;
        }
        $this->core->session->start();
        /*
         * initialization
         */
        
        if(!$this->core->session->exists("usersys")){
            $this->core->session->set("usersys",rand(10,100));
        }
        /*
         * access lists detection (guest or user)
         */
        if(!$this->core->session->exists("usergroup")){
            $this->SetupGuest();
        } else {
            $this->LaunchAccess($this->core->session->get("usergroup"));
        }
        $this->userID  = $this->core->session->get("userid");
        $this->processUserStart();
    }

    private function processUserStart(){

        
        $this->inAlready    = $this->IsInSystem();
        $this->UserName     = ($this->core->session->exists("username"))?$this->core->session->get("username"):null;
        $this->userGroup    = ($this->core->session->exists("usergroup"))?$this->core->session->get("usergroup"):$this->userGroup;
        $this->LoggedIn();
    }

    public function newuser(){
        
    }

    public function newgroup(){

    }

    public function deleteuser(){

    }

    public function deletegroup(){
        
    }


	
	private function LoggedIn(){
			
		if((int)$this->GetUserID()!=0 && $this->CheckUser()){
			$this->core->dbo->update("users_session"," set user_id='".$this->GetUserID()."' where session_id='".$this->core->session->getSessionId()."'");
			}
	}
	
	public function IsInSystem(){
		if(	isset($_COOKIE[$this->core->session->getSessionName()])
			&& $this->core->session->exists("usergroup")
			&& $this->core->session->exists("userid")
			&& $this->core->session->exists("username")
			&& $this->core->session->get("userid")!=0
			)
			{
			return true;
			}
		else
			{	
			return false;		
			}	
		}
		
	public function SysExit(){
			$this->core->session->delete("userhash");
			$this->core->session->delete("username");
			$this->core->session->delete("userid");
			$this->core->session->delete("usergroup");
			$this->core->session->destroymysession();
			return true;	
		}
			
	public function SysAuth($email,$passwd,$remember=false,$header=false){
		$subsql=" where email='".$this->core->escapeString($email)."' and passwd='".$this->core->encodeString($passwd)."' limit 1 offset 0";
		$Query=$this->core->dbo->select($this->UserTable,"id,firstname,lastname,hash,changemod,changeaccess,groupid",$subsql,_RESULT_ROW);
                if(count($Query)!=0 && !$this->inAlready){
			$this->core->dbo->update("users","  set  lastip ='".$this->core->escapeString( isset($_SERVER["REMOTE_ADDR"])?$_SERVER["REMOTE_ADDR"]:"0.0.0.0" )."',  lastdate ='".date("Y-m-d H:i:s")."' where  id ='".$Query["id"]."'");
			$this->core->session->set("username",$Query["firstname"]." ".$Query["lastname"]);
			$this->core->session->set("userid",$Query["id"]);
			$this->core->session->set("usergroup",$Query["groupid"]);
                        $this->UserName = $Query["firstname"]." ".$Query["lastname"];
                        $this->userID   = $Query["id"];
			if($remember){
				$this->inAlready=true;
				$this->core->session->resetLifetime(2678400); // Remember for a month
			}
			$this->core->log->write("user $email entered".($remember?" with remembering":null),_LOG_MESSAGE,_AUTH_LOG);
			if( $header)
				$this->core->cms->redirect();
			return true;
			}else
				return false;
		}	
		
	private function SetupGuest(){
		$this->core->DEBUG("USER","Setup-Guest Function");
		if( !$this->core->session->exists("usergroup")){
								
			$this->GetGuestFunctions();
			$this->core->session->set("userid",0);
			if($this->core->session->exists("userhash"))$this->core->session->delete("userhash");
			if($this->core->session->exists("username"))$this->core->session->delete("username");
		}
		return true;
	}
		
	private function GetGuestFunctions(){
		$this->userAccess=array_merge($this->userAccess,$this->core->dbo->select("actions","hash"," where  guest ='1'",_RESULT_LIST));


        }
	/*
	 * TODO:
	 * users accessing functions
	 */
	private function LaunchAccess($group){
		
		$Query=$this->core->dbo->select("groups","access"," where  id ='".$this->core->escapeString($group)."' limit 1 offset 0",_RESULT_ROW);
		if(count($Query)!=1)return false;
		$this->userAccess=array_merge($this->userAccess,explode(",",$Query["access"]));
		$this->GetGuestFunctions();
		$this->core->debug("user","user access settings loaded");
		return true;
	}
	
	public function resetaccess(){
		$group = $this->GetUserGroup();
		if( $group==0)
			return false;
		$time = microtime(1);
		$Query=$this->core->dbo->select("groups","access"," where  id ='".$this->core->escapeString($group)."' limit 1 offset 0",_RESULT_ROW);
		if(count($Query)!=1)return false;
		$this->userAccess=array_merge($this->userAccess,explode(",",$Query["access"]));
		$this->GetGuestFunctions();
		$this->core->debug("user","user access settings loaded");
		return true;		
	}
	


    public function GetUserID(){
        return $this->userID;
    }

    public function GetUserGroup(){
        return $this->userGroup;
    }


    public function GetUserFingerprint(){
        return $this->userID."@".$this->GetUserName();
    }

    public function  GetUserAccess(){
        return $this->userAccess;
    }

    public function checkaccess($hash){
        return (bool)in_array($hash,$this->userAccess);
    }

    public function GetChangeAccess(){
        return $this->changeAccess;
    }
    public function GetUserIP(){
        return $_SERVER["REMOTE_ADDR"];
    }

    public function GetChangeMod(){
        return $this->changeMod;
    }

    public function GetUserName(){
        return ($this->UserName!=null)?$this->UserName:"guest";
    }

    public function CheckUser(){
        return $this->inAlready;
    }

}